#include "vendors.h"
#include "util.h"
#include "re.h"

VENDORS * search_vendors(char *name) {

   FILE *fp;
   VENDORS *vendors;
   RE *re;
   char buffer[1024],pattern[512];
   int i=0;

   vendors = (VENDORS *) calloc(0, sizeof(VENDORS) );
   re = (RE *) malloc(sizeof(RE));
   fp = fopen("vendors.txt", "r");
   if(fp == NULL) _die("impossivel abrir arquivo vendors.txt");

   sprintf(pattern, "^([^;]*%s[^;]*);.*", name);

   while( fgets(buffer,1024, fp) != NULL) {

      if( matcher(pattern, buffer, re) == 0) {

         vendors = (VENDORS *) realloc(vendors, (i+1)*sizeof(VENDORS) );
         if(vendors == NULL) _die("nao foi possivel realocar vendors");

         vendors[i].name = re_copy(re, 1, buffer);
         vendors[i].code = re_copy(re, 1, buffer);
         vendors[i].active = 1;

         i++;

      }

   }

   return vendors;

}
